﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace PowerControl.Services
{
    public class BackService
    {
        int Flag = 0;
        DataTable tb = new DataTable();
        int SendCount = 0;
        IPAddress ServerIp = IPAddress.Parse(ConfigurationManager.AppSettings["MessHost1"].ToString());

        private Semaphore m_maxNumberAcceptedClients; //限制访问接收连接的线程数，用来控制最大并发数

        //IPEndPoint iep = new IPEndPoint(ServerIp, 6006);
        //Socket _newSocket;
        //IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
        //Socket _socket = new SocketSend(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Socket socket;
        Thread mythread;
        private static ConcurrentDictionary<string, string> hashpoint = new ConcurrentDictionary<string, string>();
        Thread insertDataBase;
        private static int COUNT = 0;

        int insertdatabaseTime = int.Parse(ConfigurationManager.AppSettings["insertDateBase"].ToString());
        DataTable dt1send = new DataTable();


        public void ServerRun()
        {
            mythread = new Thread(new ThreadStart(BeginListen))
            {
                IsBackground = true
            };
            mythread.Start();

            insertDataBase = new Thread(new ThreadStart(InsertListen))
            {
                IsBackground = true
            };
            insertDataBase.Start();
        }

        public string changetwoX(string hex)
        {
            if (hex.Length < 2)
                return "0" + hex;
            else
                return hex;
        }

        private void BeginListen()
        {
            //IPAddress ServerIp = IPAddress.Parse("192.168.1.13");

            IPEndPoint iep = new IPEndPoint(IPAddress.Any, int.Parse(System.Configuration.ConfigurationManager.AppSettings["MessPort1"].ToString()));

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(iep);

            int maxCount = int.Parse(System.Configuration.ConfigurationManager.AppSettings["time"].ToString());
            this.socket.Listen(maxCount);
            Power.Write2("-----------服务器监听启动-----------");

            while (true)
            {
                try
                {
                    Socket _newSocket = this.socket.Accept();

                    ThreadPool.QueueUserWorkItem(new WaitCallback(this.Start_Thread), _newSocket);
                }
                catch (Exception ex)
                {
                    Power.Write2("-------------------异常003_--------------");
                    Power.Write2(ex.StackTrace);
                    Power.Write2(ex.Message.ToString());
                }
                // PowerCard.Power.Write2("-------------------COUNT_--------------" + COUNT);
            }
        }

        private void Start_Thread(Object _newSocket)
        {

            //Power.Write2("Socket建立等待心跳包！");
            Socket newSocket = (Socket)_newSocket;
            var aa = newSocket.RemoteEndPoint.ToString();

            Console.WriteLine($"收到 {aa} 的连接消息");
            newSocket.NoDelay = true;
            newSocket.LingerState = new LingerOption(true, 10);
            newSocket.ReceiveTimeout = int.Parse(System.Configuration.ConfigurationManager.AppSettings["timeOut"].ToString());

            try
            {
                byte[] byteMessage;
                byteMessage = new byte[1024];

                if (!newSocket.Connected)
                {
                    //PowerCard.Power.Write2("-------------------UnConnected--------------");
                    newSocket.Close();
                    return;
                }

                Interlocked.Increment(ref COUNT);
                //PowerCard.Power.Write2("-------------------Receive--------------");
                var len = newSocket.Receive(byteMessage);

                string nn = System.Text.Encoding.Default.GetString(byteMessage, 0, len);

                Console.WriteLine($"收到消息 {nn}");
                // newSocket.Send(Encoding.UTF8.GetBytes(nn));
                var meterNo = nn.Split(',')[0].Trim();

                Power.WriteLog($"-------------收到心跳消息 {nn}---------------");


                if (!hashpoint.ContainsKey(meterNo))
                {
                    hashpoint.TryAdd(meterNo, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                string sql12 = "SELECT * FROM meter_operation WHERE MO_State in (0,-10,-20) AND MO_MC_No='" + meterNo + "' AND (MO_Expect_Date IS NULL OR MO_Expect_Date <='" + DateTime.Now.ToString() + "') ORDER BY MO_Id ASC limit 50;";

                DataTable tb11 = DBClass.GetDataTable1(sql12);

                int a = 0;

                foreach (DataRow rw in tb11.Rows)
                {
                    //TODO 电表编号长度小于8，信息有误？
                    if (rw["MO_MB_No"].ToString().Length < 8)
                    {
                        string sql1 = "UPDATE meter_operation SET MO_State=-30,MO_Recive_Date=NOW() WHERE MO_Id=" + rw["MO_Id"].ToString();
                        DBClass.ExeNonQuery(sql1);
                        continue;
                    }

                    SocketSend ss = new SocketSend();
                    a = ss.Send_SMS_Point(newSocket, rw);

                    if (a == -1)
                    {
                        continue;
                    }

                    string sqlsenddate = "UPDATE meter_operation Set MO_Send_Date=NOW() WHERE MO_Id=" + rw["MO_Id"].ToString();
                    DBClass.ExeNonQuery(sqlsenddate);
                    //DBClass.ExeNonQuery1(sqlsenddate);
                    //Thread.Sleep(1500);
                }

            }
            catch (Exception ex)
            {
                Power.Write2("-------------------异常001_--------------");
                Power.Write2(ex.StackTrace);
                Power.Write2(ex.Message.ToString());
            }
            finally
            {
                try
                {
                    Interlocked.Decrement(ref COUNT);
                    if (newSocket.Connected)
                    {
                        newSocket.Shutdown(SocketShutdown.Both);
                    }
                    newSocket.Close();
                }
                catch (Exception e)
                {
                    Power.Write2("-------------------异常001_1--------------");
                    Power.Write2(e.StackTrace);
                    Power.Write2(e.Message.ToString());
                }
            }
        }


        private void InsertListen()
        {
            while (true)
            {
                try
                {
                    Power.Write2("-------------------hashpoint长度_--------------" + hashpoint.Count.ToString());
                    string sqltime = "";
                    foreach (var de in hashpoint)
                    {
                        sqltime += "Update meter_collector SET MC_Create_Date='" + de.Value + "' WHERE MC_No='" + de.Key + "';";
                    }
                    hashpoint.Clear();
                    if (!string.IsNullOrEmpty(sqltime))
                    {
                        Power.Write2("-------------------更新采集器时间--------------");
                        DBClass.ExeNonQuery(sqltime);
                    }

                    //dt1send = DBClass.GetDataTable("SELECT MC_No FROM meter_collector");
                    Thread.Sleep(insertdatabaseTime);
                }
                catch (Exception ex)
                {
                    Power.Write2("-------------------异常002_--------------");
                    Power.Write2(ex.StackTrace);
                    Power.Write2(ex.Message.ToString());
                }
            }
        }
    }
}
